import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { StatePagingType } from "..";
import RequestStatus from "../RequestStatus";
import { builderPagingHandler } from ".";
import UserStorage from "storage/local/UserStorage";
import {SecurityRole} from "type/entity/SecurityRole";
import {fetchAddRole, fetchDeleterRole, fetchRolePageData, fetchUpdateRole} from "../async-action/roleAsyncAction";

export type RoleState = StatePagingType<SecurityRole>;
const initialState: RoleState = {
    data: [],
    loading: false,
    requestStatus: RequestStatus.INIT,
    currentPage: 1,
    pageSize: UserStorage.getInstance().getAdminPageConfigFromLocalStore().rolePageSize,
    total: 0,
    totalPage: 5
};

const roleSlice = createSlice({
    name: 'role',
    initialState,
    reducers: {
        /**
         * 使用roleId删除角色
         * @param state RoleState state
         * @param action PayloadAction<number> roleId
         */
        deleteRoleById: (state, action: PayloadAction<number>) =>{
            state.data = state.data.filter(role => role.id !== action.payload);
        }
    },
    extraReducers: (builder) => {
        builderPagingHandler(builder, fetchRolePageData);
        // 添加角色
        builder.addCase(fetchAddRole.fulfilled, (state, action) => {
            if(action.payload.success){
                state.requestStatus = RequestStatus.REFRESH;
            }
        });
        // 更新角色
        builder.addCase(fetchUpdateRole.fulfilled, (state, action) => {
            if(action.payload.success){
                state.requestStatus = RequestStatus.REFRESH;
            }
        });
        // 删除角色
        builder.addCase(fetchDeleterRole.fulfilled, (state, action) => {
            if(action.payload.success){
                state.requestStatus = RequestStatus.REFRESH;
            }
        });

    }
});


export const {deleteRoleById} = roleSlice.actions;
export default roleSlice.reducer;
